﻿'         This file is Copyright © 2008-2012 Billy O'Neal and Aommaster
'                            All rights reserved.
'
' This file is released under the 2-Clause BSD license, included in LICENSE.TXT
'                           and on the MHWT website
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Security.AccessControl
Imports Microsoft.Win32

Friend Class PrimaryUI

    Private Sub CascadeToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles CascadeToolStripMenuItem.Click
        Me.LayoutMdi(MdiLayout.Cascade)
    End Sub

    Private Sub TileVerticalToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles TileVerticalToolStripMenuItem.Click
        Me.LayoutMdi(MdiLayout.TileVertical)
    End Sub

    Private Sub TileHorizontalToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles TileHorizontalToolStripMenuItem.Click
        Me.LayoutMdi(MdiLayout.TileHorizontal)
    End Sub

    Private Sub CloseAllToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles CloseAllToolStripMenuItem.Click
        ' Close all child forms of the parent.
        For Each ChildForm As Form In Me.MdiChildren
            ChildForm.Close()
        Next
    End Sub
    Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim childForm As New FixForm(New Topic)
        childForm.MdiParent = Me
        childForm.Show()
    End Sub

    Private Sub ScratchPadToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ScratchPadToolStripMenuItem.Click
        Dim childFrm As New ScratchPad
        childFrm.MdiParent = Me
        childFrm.Show()
    End Sub

    Private Sub OptionsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OptionsToolStripMenuItem.Click
        Dim childForm As New GlobalSettings
        childForm.MdiParent = Me
        childForm.Show()
    End Sub

    Private Sub OutstandingTopicsToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TopicsToolStripMenuItem1.Click
        Dim childFrm As New Topics
        childFrm.MdiParent = Me
        childFrm.Show()
    End Sub

    Private Sub CannedSpeechDatabaseToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CannedSpeechDatabaseToolStripMenuItem1.Click
        Dim child As New SpeechDatabase
        child.MdiParent = Me
        child.Show()
    End Sub

    Private Sub PrimaryUI_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        For Each item As Form In MdiChildren
            item.Close()
        Next
        Dim fs As New IO.FileStream(System.IO.Path.Combine(Application.StartupPath, "Data.db"), IO.FileMode.Create)
        Dim formatter As New BinaryFormatter
        Dim temp As New DataFrontend
        formatter.Serialize(fs, temp)
        fs.Close()
    End Sub

    Private Sub PrimaryUI_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        My.Computer.Registry.CurrentUser.CreateSubKey("SOFTWARE\BillyOneal\MHWT")
        Dim regKey As Microsoft.Win32.RegistryKey = My.Computer.Registry.CurrentUser.OpenSubKey("SOFTWARE\BillyOneal\MHWT", True)
        Try
            If Me.WindowState = FormWindowState.Maximized Then
                regKey.SetValue("Maximized", True)
            Else
                regKey.SetValue("Maximized", False)
            End If
            regKey.SetValue("X", CInt(Me.Bounds.X))
            regKey.SetValue("Y", CInt(Me.Bounds.Y))
            regKey.SetValue("W", CInt(Me.Bounds.Width))
            regKey.SetValue("H", CInt(Me.Bounds.Height))
        Catch ex As Exception
            MsgBox("Failed to save window state.")
        End Try
        regKey.Close()

        Dim tempfolder As String = Environment.GetEnvironmentVariable("TEMP")
        Dim file(1) As String
        file(0) = System.IO.Path.Combine(tempfolder, "preview.html")
        file(1) = System.IO.Path.Combine(tempfolder, "help.chm")
        For i = 0 To 1
            If System.IO.File.Exists(file(i)) Then
                Try
                    System.IO.File.Delete(file(i))
                Catch
                End Try
            End If
        Next

    End Sub

    Private Sub PrimaryUI_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        Dim tempfolder As String = Environment.GetEnvironmentVariable("TEMP")
        Try
            Dim regKey As Microsoft.Win32.RegistryKey = My.Computer.Registry.CurrentUser.OpenSubKey("SOFTWARE\BillyOneal\MHWT\", False)
            Dim max As Boolean = CBool(regKey.GetValue("Maximized"))
            Dim x As Int32 = CInt(regKey.GetValue("X"))
            Dim y As Int32 = CInt(regKey.GetValue("Y"))
            Dim width As Int32 = CInt(regKey.GetValue("W"))
            Dim height As Int32 = CInt(regKey.GetValue("H"))
            If max Then
                Me.WindowState = FormWindowState.Maximized
            Else
                Me.SetBounds(x, y, width, height)
            End If
        Catch ex As Exception
            Me.WindowState = FormWindowState.Maximized
        End Try
        GlobalData.options.reset()
        Dim fs As IO.FileStream
        Try
            fs = New IO.FileStream(System.IO.Path.Combine(Application.StartupPath, "Data.db"), IO.FileMode.Open)
            Dim serializer As New BinaryFormatter
            Dim temp As New DataFrontend
            temp = DirectCast(serializer.Deserialize(fs), DataFrontend) 'This is the line that causes trouble
            temp.Writeback()
            fs.Close()
            Dim opts As GlobalOptions = GlobalData.options
        Catch ex As Exception
            GlobalData.options.reset()
            Dim regKey As RegistryKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\BillyONeal\MHWT")
            regKey.SetValue("Maximized", True)
            MsgBox("There was an error loading your settings." + Environment.NewLine + "If this is the first time you've used this program, this error is normal.")
            MsgBox("Error is: " + ex.Message)
        End Try
        System.IO.File.WriteAllBytes(System.IO.Path.Combine(tempfolder, "Help.chm"), My.Resources.Help)

        If GlobalData.options.makebackups = True Then
            Try
                Dim regKey As Microsoft.Win32.RegistryKey = My.Computer.Registry.CurrentUser.OpenSubKey("SOFTWARE\BillyOneal\MHWT\", True)
                Dim backupdate As Date = CDate(regKey.GetValue("Date"))
                If backupdate.AddDays(CDbl(GlobalData.options.backupdays)) < Date.Now Then

                    regKey.SetValue("Date", CStr(Date.Now))
                    BackupToolStripMenuItem_Click(sender, e)
                End If
            Catch ex As Exception
                MsgBox("Error making backup")
            End Try
        End If

    End Sub

    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        Dim chld As New AboutBox
        chld.MdiParent = Me
        chld.Show()
    End Sub

    Private Sub LicenceToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LicenceToolStripMenuItem.Click
        Dim chld As New License
        chld.MdiParent = Me
        chld.Show()
    End Sub

    Private Sub NormalizerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NormalizerToolStripMenuItem.Click
        Dim chld As New Normalizer
        chld.MdiParent = Me
        chld.Show()
    End Sub
    Private Sub WaitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles WaitToolStripMenuItem.Click
        Try
            My.Computer.Clipboard.SetText(GlobalData.options.logwait)
        Catch ex As Exception
            MsgBox("No wait speech has been defined", , "Error")
        End Try

    End Sub

    Private Sub StaleToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StaleToolStripMenuItem.Click
        Try
            My.Computer.Clipboard.SetText(GlobalData.options.logStale)
        Catch ex As Exception
            MsgBox("No stale log speech has been defined", , "Error")
        End Try
    End Sub

    Private Sub ResolvedToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ResolvedToolStripMenuItem.Click
        Try
            My.Computer.Clipboard.SetText(GlobalData.options.logResolved)
        Catch ex As Exception
            MsgBox("No resolved log speech has been defined", , "Error")
        End Try
    End Sub
    Function ShowHelp() As System.Diagnostics.Process Handles HelpToolStripMenuItem.Click
        Dim startInfo As New Diagnostics.ProcessStartInfo()
        Dim tempfolder As String = Environment.GetEnvironmentVariable("TEMP")

        With startInfo
            startInfo.FileName = System.IO.Path.Combine(tempfolder, "Help.chm")
            startInfo.WindowStyle = ProcessWindowStyle.Normal
        End With
        Return System.Diagnostics.Process.Start(startInfo)
    End Function
    Public Sub BackupToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BackupToolStripMenuItem.Click
        Dim opts As GlobalOptions = GlobalData.options
        Dim retvalue As Integer = 0
        Dim filename As String = ""
        Dim number As String = ""
        Dim filelist() As String


        'Sort out the hassle with file paths
        If System.IO.Directory.Exists(opts.defaultsavefolder) = False Then
            If sender.ToString() = "-1" Then
                Return
            Else
                retvalue = MsgBox("Do you want to create/select a special folder to store the backups?" & Environment.NewLine & "YES to designate the folder" & Environment.NewLine & "NO to backup in working directory" & Environment.NewLine & "CANCEL to cancel Backup", MsgBoxStyle.YesNoCancel, "Creating Backup")
                If retvalue = 6 Then
                    SelectFolderToolStripMenuItem_Click(-1, e)
                    If opts.defaultsavefolder = "" Then
                        Return
                    End If
                ElseIf retvalue = 7 Then
                    opts.defaultsavefolder = Application.StartupPath
                Else
                    Return
                End If
            End If
        End If

        'Sort out the filename
        number = DateTime.Now.Day.ToString()
        If number.Length <> 2 Then
            filename = filename & "0" & number & "-"
        Else
            filename = filename & number & "-"
        End If
        number = DateTime.Now.Month.ToString()
        If number.Length <> 2 Then
            filename = filename & "0" & number & "-"
        Else
            filename = filename & number & "-"
        End If
        number = DateTime.Now.Year.ToString()
        filename = "Data" & " " & filename & number & ".db.bak"

        'Sort out the prefix
        filelist = System.IO.Directory.GetFiles(opts.defaultsavefolder, "*.db.bak")
        number = (UBound(filelist) + 2).ToString
        If number.Length = 1 Then
            filename = "00" & number & " " & filename
        ElseIf number.Length = 2 Then
            filename = "0" & number & " " & filename
        ElseIf number.Length = 3 Then
            filename = number & " " & filename
        Else
            MsgBox("Too many backups. Backup file name changed to Data ""DD-MM-YYYY.db.bak""")
        End If

        Try
            System.IO.File.Copy(System.IO.Path.Combine(Application.StartupPath, "data.db"), System.IO.Path.Combine(opts.defaultsavefolder, filename))
            MsgBox("Backup successfully made at:" & Environment.NewLine & System.IO.Path.Combine(opts.defaultsavefolder, filename), , "Backup created")
        Catch ex As Exception
            MsgBox("Unable to write file. Make sure the backup directory is not write protected", , "Error")
        End Try



    End Sub

    Private Sub SelectFolderToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SelectFolderToolStripMenuItem.Click
        Dim opts As GlobalOptions = GlobalData.options
        Dim browser As New FolderBrowserDialog

        opts.defaultsavefolder = ""

        With browser
            .RootFolder = Environment.SpecialFolder.Desktop
            .SelectedPath = Environment.SpecialFolder.Desktop.ToString
            .Description = "Select the source directory"
            If .ShowDialog = DialogResult.OK Then
                opts.defaultsavefolder = .SelectedPath
            Else
                opts.defaultsavefolder = ""
            End If
        End With

        BackupToolStripMenuItem_Click(-1, e)
    End Sub

    Private Sub CommandListToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CommandListToolStripMenuItem.Click
        Dim chld As New SyntaxGuide
        chld.MdiParent = Me
        chld.Show()
    End Sub

    Private Sub ArchiveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ArchiveToolStripMenuItem.Click
        Dim childFrm As New Archive
        childFrm.MdiParent = Me
        childFrm.Show()
    End Sub

    Private Sub StatisticsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StatisticsToolStripMenuItem.Click
        Dim childFrm As New Stats
        childFrm.MdiParent = Me
        childFrm.Show()
    End Sub

    Private Sub HexConverterToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HexConverterToolStripMenuItem.Click
        Dim childFrm As New HexConvert
        childFrm.MdiParent = Me
        childFrm.Show()
    End Sub

    Private Sub HasherToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HasherToolStripMenuItem.Click
        Dim childFrm As New Hasher
        childFrm.MdiParent = Me
        childFrm.Show()
    End Sub

End Class